package org.lim.lcpicturebackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.lim.lcpicturebackend.mapper.PictureTagMapper;
import org.lim.lcpicturebackend.model.entity.PictureTag;
import org.lim.lcpicturebackend.service.PictureTagService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 图片标签服务实现类
 */
@Service
public class PictureTagServiceImpl extends ServiceImpl<PictureTagMapper, PictureTag> implements PictureTagService {

    @Override
    public List<PictureTag> getActiveTagList() {
        QueryWrapper<PictureTag> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_active", 1)
                .orderByAsc("sort_order", "id");
        return this.list(queryWrapper);
    }

    @Override
    public PictureTag getByTagName(String tagName) {
        QueryWrapper<PictureTag> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tag_name", tagName);
        return this.getOne(queryWrapper);
    }

    @Override
    public boolean batchAddTags(List<String> tagNames) {
        if (CollectionUtils.isEmpty(tagNames)) {
            return true;
        }

        AtomicInteger sortOrder = new AtomicInteger(1);
        List<PictureTag> tagList = tagNames.stream()
                .filter(tagName -> tagName != null && !tagName.trim().isEmpty())
                .map(tagName -> {
                    PictureTag tag = new PictureTag();
                    tag.setTagName(tagName.trim());
                    tag.setSortOrder(sortOrder.getAndIncrement());
                    tag.setIsActive(1);
                    tag.setCreateTime(new Date());
                    tag.setUpdateTime(new Date());
                    return tag;
                })
                .toList();

        return this.saveBatch(tagList);
    }
}